
import {createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

import routes from './routerOptions'
import globalStore from '/src/components/pinia/store.js'
import cookieApi from '/src/api/cookie_api.js'
import uApi from '/src/api/base/u_api.js'

const basePath = import.meta.env.VITE_FRONT_BASE
const manageRoot = import.meta.env.VITE_MANAGE_ROOT

const router = createRouter({
  //   history: VueRouter.createWebHashHistory(),
  // history: createWebHistory('/coco'),
  history: createWebHistory(basePath),
  routes,
})

const LOGIN_PATH = "/login"
const checkRemember = async (to, from) => {
  // 从 cookie 中设置 token
  // 从 cookie 中读取 token, 同时获取用户信息
  let store = globalStore()
  if(store.token) {
    return
  }

  let authHeader = import.meta.env.VITE_HEADER_AUTH
  let authCookieName = import.meta.env.VITE_COOKIE_AUTH
  // console.log('cookies', cookieApi.allCookies())

  if(authHeader && authCookieName) {
    let cookieValue = cookieApi.getCookie(authCookieName)
    // console.log('cookies-token', cookieValue, store.userinfo)

    let isManage = to.fullPath.startsWith(manageRoot)

    // 如果是进入登录页面，则不发送请求
    // console.log(to.path)
    if ( to.path === LOGIN_PATH ) {
      return
    }

    // 其他页面正常查询用户数据
    if(cookieValue && !store.userinfo) {
      let requestMethod = isManage ? uApi.currentAdminInfo : uApi.currentUserInfo
      await requestMethod().then((res) => {
        store.setToken(res.data?.token, false)
        store.setUserinfo(res.data)
        // console.log("currentAdminInfo-res", store.token)
      }, err => {
        console.error(err)
        // 失败了就该跳转到登录页面
        //console.log(from)
        router.push('/login?from='+encodeURI(window.location.href))
        //Message.error( err.message, { closable: true, duration: 5000 } )
      })
    }
  }
}

router.beforeEach( async (to, from, next) => {
  await checkRemember(to, from)
  // console.log("route-change")
  // TODO 跳转到需要权限的页面，预先检查权限
  next()
})

export default router